#!/usr/bin/perl

use Test;
BEGIN { plan tests => 6 }

$basedir = $0;
$basedir =~ s|(.*)/[^/]*|$1|;

# Remove any leftover test directory from prior failed runs.
system("rm -rf $basedir/test_dir");

# Create a test directory with the test_addname_dir_t type for use in the tests.
system("mkdir $basedir/test_dir 2>&1");
system("chcon -t test_link_dir_t $basedir/test_dir");

# Create a test file with the test_link_file_t type.
system("touch $basedir/test_dir/test_file");
system("chcon -t test_link_file_t $basedir/test_dir/test_file");

# Verify that test_link_t can create another hard link to the test file
# in the test directory.
$result = system(
"runcon -t test_link_t ln $basedir/test_dir/test_file $basedir/test_dir/test_link 2>&1"
);
ok( $result, 0 );

# Verify that test_nolink_t cannot create a hard link to the test file.
# Should fail on the link permission check.
$result = system(
"runcon -t test_nolink_t ln $basedir/test_dir/test_file $basedir/test_dir/test_link2 2>&1"
);
ok($result);

# Verify that test_nolink2_t cannot create a hard link in the test directory.
# Should fail on the add_name permission check.
$result = system(
"runcon -t test_nolink2_t ln $basedir/test_dir/test_file $basedir/test_dir/test_link3 2>&1"
);
ok($result);

# Verify that test_unlink_t can remove a hard link to the test file.
$result =
  system("runcon -t test_unlink_t -- rm -f $basedir/test_dir/test_link 2>&1");
ok( $result, 0 );

# Verify that test_nounlink_t cannot remove a hard link to the test file.
# Should fail on the unlink permission check.
$result =
  system("runcon -t test_nounlink_t -- rm -f $basedir/test_dir/test_file 2>&1");
ok($result);

# Verify that test_nounlink2_t cannot remove a hard link in the test directory.
# Should fail on the remove_name permission check.
$result = system(
    "runcon -t test_nounlink2_t -- rm -f $basedir/test_dir/test_file 2>&1");
ok($result);

# Cleanup.
system("rm -rf $basedir/test_dir");

